from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import os
import mysql.connector
from mysql.connector import Error

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# 数据库配置
db_config = {
    'host': '10.200.36.30',
    'user': 'root',  # 替换为你的数据库用户名
    'password': '111111',  # 替换为你的数据库密码
    'database': 'f21010319'
}


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'image' not in request.files:
        return redirect(request.url)
    file = request.files['image']
    if file.filename == '':
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)

        question = request.form['question']
        try:
            conn = mysql.connector.connect(**db_config)
            cursor = conn.cursor()
            cursor.execute("INSERT INTO questions (image_path, question_text) VALUES (%s, %s)", (file_path, question))
            conn.commit()
            cursor.close()
            conn.close()
            return 'File uploaded and saved to database successfully'
        except Error as e:
            print(e)
            return 'Error occurred while connecting to MySQL database'
    return 'Invalid file type'


if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run(debug=True)